<template>
  <div class="home-container">
    <!-- 统计卡片区块 -->
    <a-row :gutter="[24, 24]" class="stats-row">
      <a-col :xs="24" :sm="12" :md="12" :lg="6" v-for="(stat, index) in statistics" :key="index">
        <a-card
          class="stats-card"
          :class="`stats-card-${index % 4}`"
          hoverable
          @click="stat.onClick"
        >
          <div class="card-header">
            <component :is="stat.icon" class="card-icon" />
            <span class="card-title">{{ stat.title }}</span>
          </div>
          <a-statistic
            :value="stat.value"
            :precision="stat.precision"
            :prefix="stat.prefix"
            :value-style="{ color: stat.color }"
            class="statistic-content"
          >
            <template #title>
              <span class="stat-subtitle">{{ stat.subtitle }}</span>
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 图表区域 -->
    <a-row :gutter="[24, 24]" class="chart-row">
      <!-- 订单趋势图 -->
      <a-col :span="16">
        <a-card
          title="订单趋势"
          :loading="loading"
          :headStyle="{ padding: '0 16px' }"
        >
          <template #extra>
            <a-radio-group
              v-model:value="trendDays"
              size="small"
              buttonStyle="solid"
              @change="handleTrendDaysChange"
            >
              <a-radio-button :value="7">近7天</a-radio-button>
              <a-radio-button :value="15">近15天</a-radio-button>
              <a-radio-button :value="30">近30天</a-radio-button>
            </a-radio-group>
          </template>
          <div id="orderTrendChart" style="height: 300px"></div>
        </a-card>
      </a-col>

      <a-col :span="8">
        <a-card title="热门商品" :loading="false" class="hot-product-card">
          <a-table
            :columns="hotProductColumns"
            :data-source="hotProductList"
            :pagination="false"
            size="small"
            :loading="hotProductLoading"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'product'">
                <a-space>
                  <a-image-preview-group>
                    <a-image
                      :src="record.image || defaultImage"
                      class="product-image"
                      :preview="{
                        src: record.image || defaultImage,
                        maskClassName: 'preview-mask'
                      }"
                      @error="handleImageError"
                    />
                  </a-image-preview-group>
                  <a-tooltip :title="record.name || '未命名商品'">
                    <span class="product-name-ellipsis">{{ truncateName(record.name || '未命名商品', 10) }}</span>
                  </a-tooltip>
                </a-space>
              </template>
              <template v-if="column.key === 'minPrice'">
                <span class="sales-count">{{ record.minPrice || 0 }}</span>
              </template>
              <template v-if="column.key === 'sales'">
                <span class="sales-count">{{ record.sales || 0 }}</span>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>

    </a-row>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import {
  ShoppingCartOutlined,
  DollarOutlined,
  UserOutlined
} from '@ant-design/icons-vue'
import { ORDER_STATUS_TEXT } from '@/constants/order'
import { useWebSocketStore } from '@/stores/WebSocket.ts'
import defaultImage from '@/assets/default.jpg'
import { getLastNDaysOrderCountUsingGet } from '@/api/orderStatsController'
import { listProductVoByPageUsingPost } from '@/api/productController'
import { useRouter } from 'vue-router'
import { USER_ROLE } from '@/constants/user'

interface DashboardData {
  todayOrders: string;
  pendingShipment: string;
  todaySales: string;
  afterSales: string;
}
import { useUserStore } from '@/stores/user'
const websocketStore = useWebSocketStore()
const url = import.meta.env.VITE_DATA_WEBSOCKET_URL
const userStore = useUserStore()

// 使用computed获取token，确保响应式更新
const token = computed(() => userStore.token)

const dashboardData = ref<DashboardData>({
  todayOrders: '0',
  pendingShipment: '0',
  todaySales: '0',
  afterSales: '0'
})

// 加载状态
const loading = ref(false)

const router = useRouter()

// 统计卡片数据
const statistics = computed(() => [
  {
    title: '今日订单',
    subtitle: '订单总数',
    value: dashboardData.value.todayOrders,
    icon: ShoppingCartOutlined,
    color: '#722ed1',
    onClick: () => router.push('/order')
  },
  {
    title: '待发货',
    subtitle: '待处理订单',
    value: dashboardData.value.pendingShipment,
    icon: ShoppingCartOutlined,
    color: '#fa8c16',
    onClick: () => router.push('/order')
  },
  {
    title: '今日销售额',
    subtitle: '销售总额',
    value: dashboardData.value.todaySales,
    precision: 2,
    prefix: '￥',
    icon: DollarOutlined,
    color: '#52c41a',
    onClick: () => router.push('/orders')
  },
  {
    title: '待处理售后',
    subtitle: '数量',
    value: dashboardData.value.afterSales,
    icon: UserOutlined,
    color: '#1890ff',
    onClick: () => router.push('/after-sales')
  }
])

// 热销商品表格列
const hotProductColumns = [
  {
    title: '商品信息',
    key: 'product',
    width: '50%',
  },
  {
    title: '最低价格',
    key: 'minPrice',
    width: '20%',
    align: 'center'
  },
  {
    title: '销量',
    key: 'sales',
    width: '25%',
    align: 'center'
  }
]

// 图片错误处理函数
const handleImageError = (e: Event) => {
  const imgElement = e.target as HTMLImageElement
  imgElement.src = <string>defaultImage
}

// 订单趋势天数选择
const trendDays = ref<number>(7)

// 订单趋势图数据
const orderTrendData = ref<{ date: string; count: number }[]>([])

// 获取订单趋势数据
const fetchOrderTrendData = async () => {
  try {
    loading.value = true
    // 清空数据，避免混合旧数据
    orderTrendData.value = []
    // @ts-ignore
    const response = await getLastNDaysOrderCountUsingGet({
    // @ts-ignore
      days: trendDays.value.toString()
    })
    if (response && response.data) {
      // 将数据转换为图表所需的格式，并格式化日期
      const data = Object.entries(response.data).map(([date, count]) => ({
        date: date.substring(5), // 去掉年份，只显示月-日
        count: parseInt(count as string)
      }))
      // 按日期排序
      data.sort((a, b) => a.date.localeCompare(b.date))
      orderTrendData.value = data
    } else {
      console.error('获取订单趋势数据失败: 接口返回错误', response)
    }
  } catch (error) {
    console.error('获取订单趋势数据失败:', error)
    orderTrendData.value = [] // 确保清空数据
  } finally {
    loading.value = false
  }
}

// 处理趋势天数变更
const handleTrendDaysChange = () => {
  if (loading.value) return // 防止重复点击
  fetchOrderTrendData().then(() => {
    nextTick(() => {
      // 确保DOM已更新后再更新图表
      updateOrderTrendChart()
    })
  })
}

// 图表实例
let orderTrendChart: echarts.ECharts | null = null
let orderStatusChart: echarts.ECharts | null = null

// 初始化订单趋势图
const initOrderTrendChart = () => {
  const chartDom = document.querySelector('#orderTrendChart') as HTMLElement
  if (!chartDom) return

  orderTrendChart = echarts.init(chartDom)

  if (orderTrendData.value.length === 0) {
    // 显示无数据状态
    orderTrendChart.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center'
      }
    })
    return
  }

  updateOrderTrendChart()
}

// 更新订单趋势图
const updateOrderTrendChart = () => {
  if (!orderTrendChart) return

  // 重新创建实例，确保图表完全重绘
  if (orderTrendChart) {
    orderTrendChart.dispose()
  }

  const chartDom = document.querySelector('#orderTrendChart') as HTMLElement
  if (!chartDom) return

  orderTrendChart = echarts.init(chartDom)

  if (orderTrendData.value.length === 0) {
    // 显示无数据状态
    orderTrendChart.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center'
      }
    })
    return
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />订单数：{c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: orderTrendData.value.map(item => item.date),
      axisLabel: {
        rotate: 45,
        interval: trendDays.value === 30 ? 'auto' : 0
      }
    },
    yAxis: {
      type: 'value',
      name: '订单数',
      minInterval: 1
    },
    series: [{
      name: '订单数',
      type: 'line',
      smooth: true,
      data: orderTrendData.value.map(item => item.count),
      itemStyle: {
        color: '#722ed1'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(114, 46, 209, 0.3)'
          },
          {
            offset: 1,
            color: 'rgba(114, 46, 209, 0.1)'
          }
        ])
      }
    }]
  }

  orderTrendChart.setOption(option)
}

// 监听数据变化，更新图表
watch(orderTrendData, () => {
  if (orderTrendData.value.length > 0) {
    updateOrderTrendChart()
  }
}, { deep: true })

// 初始化订单状态分布图
const initOrderStatusChart = () => {
  const chartDom = document.querySelector('#orderStatusChart') as HTMLElement
  if (!chartDom) return

  orderStatusChart = echarts.init(chartDom)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: [
          { value: 235, name: ORDER_STATUS_TEXT.pending },
          { value: 274, name: ORDER_STATUS_TEXT.paid },
          { value: 310, name: ORDER_STATUS_TEXT.shipped },
          { value: 335, name: ORDER_STATUS_TEXT.completed },
          { value: 100, name: ORDER_STATUS_TEXT.cancelled }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  orderStatusChart.setOption(option)
}

// 图表自适应
const handleResize = () => {
  orderTrendChart?.resize()
  orderStatusChart?.resize()
}

// 解析数据
const updateDashboard = (data: DashboardData) => {
  dashboardData.value = data;
  // 不需要再单独更新 statistics，因为它是计算属性，会自动响应 dashboardData 的变化
};

// 热门商品数据
const hotProductList = ref<API.ProductVO[]>([])
const hotProductLoading = ref(false)

// 初始化图表和WebSocket连接
onMounted(async () => {
  // 获取订单趋势数据
  await fetchOrderTrendData()
  // 获取热销商品数据
  await fetchHotProducts()
  // 初始化图表
  initOrderTrendChart()

  // 构建带token的WebSocket URL
  const wsUrl = `${url}${token.value}`
  console.log('WebSocket URL:', wsUrl)

  // 创建单个WebSocket连接，处理两种消息类型
  websocketStore.createConnection(
    'dashboard',
    wsUrl,
    (event: MessageEvent) => {
      try {
        const data = JSON.parse(event.data)
        if (data) {
          // 更新仪表盘数据
          updateDashboard(data)
        }
      } catch (error) {
        console.error('解析WebSocket消息失败:', error)
      }
    }
  )
})

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  websocketStore.closeConnection('dashboard')
})
const fetchHotProducts = async () => {
  try {
    hotProductLoading.value = true


    const response = await listProductVoByPageUsingPost({
      pageSize: 5,
      current: 1,
      sortField: 'sales',
      sortOrder: 'desc'
    })

    // 处理API响应数据
    if (response && response.data) {
      const apiData = response.data as any

      if (apiData.records && Array.isArray(apiData.records)) {
        hotProductList.value = apiData.records
      } else if (Array.isArray(apiData)) {
        hotProductList.value = apiData
      } else {
      }
    }
  } catch (error) {
    console.error('获取热门商品数据失败:', error)
  } finally {
    hotProductLoading.value = false
  }
}

// 截断商品名称
const truncateName = (name: string, length: number) => {
  if (!name) return '';
  return name.length > length ? name.substring(0, length) + '...' : name;
}

onMounted(() => {
  // 先获取数据，再初始化图表
  fetchOrderTrendData().then(() => {
    initOrderTrendChart()
  })
  // 获取热门商品数据
  fetchHotProducts()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  orderTrendChart?.dispose()
  window.removeEventListener('resize', handleResize)
  websocketStore.closeConnection('dashboard')
})
</script>

<style scoped lang="scss">
.home-container {
  padding: 24px;
  background: #f0f2f5;
}

.stats-row {
  margin-bottom: 24px;
}

.chart-row {
  margin-bottom: 24px;
}

.table-row {
  margin-bottom: 24px;
}

.stats-card {
  border-radius: 8px;
  transition: transform 0.3s;
  cursor: pointer;

  &:hover {
    transform: translateY(-4px);
  }
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .card-icon {
    font-size: 24px;
    margin-right: 12px;
  }

  .card-title {
    font-size: 16px;
    font-weight: 500;
  }
}

.product-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;

  /*&:hover {
    transform: scale(1.05);
  }*/
}

:deep(.ant-image) {
  width: 40px !important;
  height: 40px !important;
}

/*:deep(.preview-mask) {
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.45);
}*/

:deep(.ant-image-preview-img) {
  // 预览时保持原始比例
  object-fit: contain;
  max-width: 90vw;
  max-height: 90vh;
}

// 统计卡片渐变背景
.stats-card-0 { background: linear-gradient(135deg, #f9f0ff, #ffffff); }
.stats-card-1 { background: linear-gradient(135deg, #fff7e6, #ffffff); }
.stats-card-2 { background: linear-gradient(135deg, #f6ffed, #ffffff); }
.stats-card-3 { background: linear-gradient(135deg, #e6f7ff, #ffffff); }

.hot-product-card {
  height: 100%;
  overflow: hidden;
}

.hot-product-list {
  height: 300px;
  overflow-y: auto;
}

.product-list-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    background-color: #f5f5f5;
  }
}

.product-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
  margin-right: 12px;
}

.product-info {
  flex: 1;
  min-width: 0;

  .product-name {
    font-weight: 500;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .product-price {
    color: #f5222d;
    font-size: 12px;
  }
}

.product-sales {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
  color: #999;

  .sales-count {
    color: #333;
    font-weight: 500;
    font-size: 14px;
  }
}

.product-name-ellipsis {
  display: inline-block;
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>

// 增加API响应类型声明
declare namespace API {
  interface ProductVO {
    id?: number;
    name?: string;
    image?: string;
    minPrice?: number;
    sales?: number;
    [key: string]: any;
  }
}
